using System.Net.NetworkInformation;
namespace TPXSDK.NET.Link;

/// <summary>
/// 通讯适配器创建工厂
/// </summary>
public static class CommFactory
{
    /// <summary>
    /// 根据描述字符串创建通讯适配器
    /// </summary>
    public static CommAdapter? Create(string strDesc)
    {
        if (string.IsNullOrEmpty(strDesc) ||
            string.IsNullOrWhiteSpace(strDesc))
        {
            return null;
        }
        strDesc = strDesc.Trim();
        try
        {
            if (strDesc.StartsWith("COM"))
            {
                return new UartAdapter(strDesc);
            }
            if (strDesc.StartsWith("TCPC"))
            {
                return new TcpClientAdapter(strDesc);
            }
            if (strDesc.StartsWith("UDPC"))
            {
                return new UdpClientAdapter(strDesc);
            }

        }
        catch
        {
            // Ignore
        }
        return null;
    }

    /// <summary>
    /// 检测指定本机端口是否被占用
    /// </summary>
    /// <returns></returns>
    public static bool IsLocalPortUsed(int port)
    {
        var properties = IPGlobalProperties.GetIPGlobalProperties();
        var udpEndPoints = properties.GetActiveUdpListeners();
        return udpEndPoints.Any(pp => pp.Port == port);
    }
}//end CommFactory
